package api

import (
	"ginfast/app/mall/dto"
	"ginfast/app/mall/model"
	"ginfast/pkg/ginx"
	"ginfast/pkg/orm"
	"ginfast/util"
)

// UserAddress 地址
type UserAddress struct {
}

// ListHandler 列表
func (UserAddress) ListHandler(c *ginx.Context) {
	var data []model.UserAddress
	err := orm.DbFind(&data)
	c.JSONWriteData(data, err)
}

// PageHandler 分页
func (UserAddress) PageHandler(c *ginx.Context) {
	var p dto.Where
	if err := c.MustBind(&p); err != nil {
		return
	}
	var data []model.UserAddress
	total, _ := p.DbModelWhere(&model.UserAddress{}).Find(&data)
	c.JSONWriteTotal(total, data)
}

// GetHandler 查询
func (UserAddress) GetHandler(c *ginx.Context) {
	util.QueryByID(&model.UserAddress{}, c)
}

// AddHandler 新增
func (UserAddress) AddHandler(c *ginx.Context) {
	var p model.UserAddress
	//获取参数
	err := c.MustBind(&p.UserAddressOpt)
	if err != nil {
		return
	}
	err = orm.DbCreate(&p)
	c.JSONWriteError(err)
}

// UpdateHandler 修改
func (UserAddress) UpdateHandler(c *ginx.Context) {
	var p model.UserAddress
	//获取参数
	err := c.MustBind(&p.UserAddressOpt)
	if err != nil {
		return
	}
	err = orm.DbUpdateModel(&p)
	c.JSONWriteError(err)
}

// DeleteHandler 删除
func (UserAddress) DeleteHandler(c *ginx.Context) {
	util.Deletes(&model.UserAddress{}, c)
}

// UpdateStatusHandler 修改
func (UserAddress) UpdateDefaultHandler(c *ginx.Context) {
	var p model.UserAddress
	//获取参数
	err := c.MustBind(&p.UserAddressOpt)
	if err != nil {
		return
	}
	err = orm.DbUpdateFields(&p, "IsDefault")
	c.JSONWriteError(err)
}

func (o UserAddress) Routers(r *ginx.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/page", o.PageHandler)
	r.GET("/:id", o.GetHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.PUT("/default", o.UpdateDefaultHandler)
}
